$(function() {
    $lang.init();
    $page.init('tag', $tag);
    $tag.init();
    //Tooltip
    $('#username, #email, #pass2').tooltip();
});

var $tag = function() {
    var $objTag = {
        fields: {
            name: 'tag_name',
            slug: 'tag_slug',
            description: 'tag_description'
        },
        init: function() {
            this._initEvent();
        },
        _initSearch: function() {
            $('#search_name, #search_slug, #search_description,\n\
                #search_number_post_from, #search_number_post_to,\n\
                #search_id_from, #search_id_to').keyup(function() {
                $objTag.refresh();
            });

            return this;
        },
        _initSort: function() {
            $('.sort').click(function($event) {
                var $column = $(this).attr('id').toString().replace('sort_', '');
                var $object = $(this);
                var $option = {
                    type: 'post',
                    url: $project.siteUrl('tag/admincp/index/ajax_sort'),
                    dataType: 'json',
                    data: {column: $column},
                    success: function($response, $status) {
                        if ($response.result) {
                            //Change arrow of column.
                            $objTag.resetSort();
                            if (!$response.data.type_sort) {
                                $('#sort_name').parent().addClass('sortdesc');
                            }
                            else {
                                $object.parent().addClass('sort' + $response.data.type_sort);
                            }
                            //Get current page....
                            var $curPage = $('#current_page_product').text();
                            $curPage = !$curPage ? 1 : $curPage;
                            $objTag.getList($curPage);
                        }
                    }
                };

                $project.ajax($option);
            });

            return this;
        },
        _initEvent: function() {
            $('input.add').click(function() {
                $dialog.container({
                    title: 'Add tag',
                    body: $project.removeComment($('#dlg_add_tag').html()),
                    buttons: {
                        Add: function() {
                            $objTag.add();
                        },
                        Reset: function() {
                            $('#form_add').get(0).reset();
                        },
                        Cancel: function() {
                            $dialog.close().destroy();
                        }
                    }
                });
            });

            //Check all product...
            $('input#all_item').click(function() {
                $('.item-select').prop('checked', this.checked);
            });

            //Delete multiple item...
            $('input#delete_item').click(function() {
                $objTag.resetDeletedItems().showDeletedItems();
            });

            //Edit a item
            $('.edit-item').live('click', function($event) {
                $event.preventDefault();
                var $id = $(this).prop('id')
                        .toString()
                        .replace('edit_item_', '');

                $tag.getById($id);
            });

            //Intialize search and sort event.
            this._initSearch()._initSort();
            return this;
        },
        refresh: function() {
            $page.get(0);
        },
        resetSort: function() {
            $('.sort').parent()
                    .removeClass('sortdesc')
                    .removeClass('sortasc');
        },
        proccessErrorAdd: function($aError) {
            $tag.resetFieldAdd();

            for ($error in $aError) {
                $('#' + $tag.fields[$error])
                        .after($aError[$error])
                        .css('border', '1px solid red');

                if (!$aError[$error]) {
                    $('#' + $tag.fields[$error]).css('border', '');
                }

                //Check if password match is match
                if ($error == 'password_match'){
                    if (!$aError[$error]) {
                        ///////////////////
                        $('#password_match').empty().html('yes');
                    }
                    else {
                        $('#password_match').empty().html('no');
                    }
                }
            }

            //////////////////////////
            $dialog.message({text: 'Please fill the field in red'});
        },
        resetFieldAdd: function() {
            $('.error-message').empty();

            for ($field in $tag.fields) {
                $('#' + $tag.fields[$field]).css('border', '');
                $('#' + $tag.fields[$field] + '+ div.error').remove('div.error');
            }
        },
        resetUploadImage: function() {
            $('div.upload-image-product + div.error').remove('div.error');
        },
        resetUploadImgInput: function() {
            $('#form_image_product').get(0).reset();
            $('div.upload-image-product + div.error').remove('div.error');
        },
        resetFormAdd: function() {
            $('#form_add').get(0).reset();
            $objTag.resetFieldAdd();
            $('#product_image').val('');
            $('#product_image + img').remove('img');
            $('#product_image + br').remove('br');
            //reset error of image field.
            $('#product_image ~ .error').remove('div');
        },
        add: function() {
            //Set cur_page to input hidden, use for reload page when edit.
            var $curPage = $('#current_page_product').text();
            $('input#product_cur_page').val(!$curPage ? 1 : $curPage);

            var $option = {
                type: 'post',
                url: $('#form_add').attr('action'),
                dataType: 'json',
                data: $('#form_add').serialize(),
                success: function($response, $status) {
                    if ($response.result) {
                        if (!$response.data.cur_page) {
                            location.reload();
                            return;
                        }

                        //In case edit page, reload that page.
                        $dialog.close().destroy();
                        /////////////////////////////
                        $page.get($response.data.cur_page);
                    }
                    else {
                        $tag.proccessErrorAdd($response.data);
                    }
                }
            };

            $.ajax($option);
        },
        getList: function($offset) {
            $page.get($offset);

            return this;
        },
        getSearchObject: function() {
            return $('#form_search').serialize();
        },
        createList: function($dataList) {
            var $data = $dataList;
            var $body = $('#body_list');
            $body.empty();

            //Check if no post in table product.
            $('#no_row').remove();

            if (!$data) {
                $body.append('<tr id="no_row" class="no-row"><td colspan="11">' + $lang.phrases.no_product + '</td></tr>');
            }

            //Traverse list product
            for (var $i = 0; $i < $data.length; $i++) {
                var $list = '';
                var $row = $data[$i];
                var $itemId = null;

                for (var $col in $row) {
                    if ($col == 'id') {
                        $itemId = $row[$col];
                    }

                    $list = this.fillData($col, $row[$col], $list);
                }

                $body.append($list);

                if ($i % 2) {
                    $('#row_' + $itemId).addClass('even');
                }
                else {
                    $('#row_' + $itemId).addClass('odd');
                }
            }
        },
        fillData: function($col, $data, $list) {
            var $tr = $('#row_item').html();
            $tr = $tr.replace(/^(<\!\-\-)|(\-\-\>)$/, '');
            if ($list) {
                $tr = $list
            }

            switch ($col) {
                case 'id':
                    $tr = $tr.replace(/{item_id}/g, $data);
                    break;
                case 'name':
                    $tr = $tr.replace(/{item_name}/g, $data);
                    break;
                case 'slug':
                    $tr = $tr.replace(/{item_slug}/g, $data);
                    break;
                case 'description':
                    $tr = $tr.replace(/{item_description}/g, $data);
                    break;
                case 'number_post':
                    $tr = $tr.replace(/{item_number_post}/g, $data);
                    break;
            }
            return $tr;
        },
        deleteProducts: function() {
            var $class = $('.item-select');
            var $ids = '{';

            for (var $item in $class) {
                if ($class[$item].checked == true) {
                    $ids += '"' + $item + '":"' + $class[$item].id + '",';
                }
            }

            $ids = $ids.replace(/,$/g, '') + '}';
            /////////////////
            var $curPage = $('#current_page_product').text();
            $curPage = !$curPage ? 1 : $curPage;

            var $option = {
                type: 'post',
                url: $project.siteUrl('tag/admincp/index/ajax_delete'),
                dataType: 'json',
                data: {item_ids: $ids, cur_page: $curPage},
                success: function($response, $status) {
                    if ($response.result) {
                        //Get list product of page.
                        ///////////////////////////
                        $page.get($response.data.page);
                    }
                }
            };

            $project.ajax($option);
            return this;
        },
        showDeletedItems: function() {
            var $class = $('.item-select');
            var $listDeleted = '';
            var $hasDelItem = false;

            for (var $item in $class) {
                if ($class[$item].checked == true) {
                    $hasDelItem = true;
                    $listDeleted += '<li class="deleted-item">' + $('#item_name_' + $class[$item].id).text() + '</li>';
                }
            }

            $listDeleted = '<ol>' + $listDeleted + '</ol>';
            //if no item is deleted that isn't show dialog.
            if ($hasDelItem) {
                //Show dialog delete item.
                $dialog.confirmExt(
                        function() {
                            $objTag.deleteProducts();
                        }, $listDeleted, 'Are you sure to delete these user(s)?');
            }

            return this;
        },
        resetDeletedItems: function() {
            //Append to section deleted product dialog.
            $('#list_deleted_item').empty();
            return this;
        },
        getById: function($id) {
            var $option = {
                type: 'post',
                url: $project.siteUrl('tag/admincp/index/ajax_get'),
                dataType: 'json',
                data: {item_id: $id},
                success: function($response, $status) {
                    if ($response.result) {
                        //populate product into edit form. and set useful.
                        $tag.populate($response.data);
                    }
                }
            };

            $project.ajax($option);
            return this;
        },
        populate: function($data) {
            $dialog.container({
                ////////////////////
                title: 'Edit tag',
                body: $project.removeComment($('#dlg_add_tag').html()),
                buttons: {
                    Update: function() {
                        $objTag.add();
                    },
                    Reset: function() {
                        $('#form_add').get(0).reset();
                    },
                    Cancel: function() {
                        $dialog.close().destroy();
                    }
                }
            });
            //Set id to edit.
            $('#' + 'tag_id').val($data.id);
            //
            $('#' + this.fields.name).val($data.name);
            $('#' + this.fields.slug).val($data.slug);
            $('#' + this.fields.description).val($data.description);
            //Change action from add to edit.
            $('#form_add').attr('action', $project.siteUrl('tag/admincp/index/ajax_save'));

            return this;
        }
    }

    return $objTag;
}();